<?php
class Merchant_Service_CustomerAddressBook
{
	protected $_table;
	public function __construct(){
		$this->_table = new Merchant_Model_CustomerAddressBook();
	}
	
	/**
	* 添加
	* @param array $row
	*/
	public function add($row,$type,$customerId=null){
		$row["customer_id"] = $this->getCustomerId($customerId);
		$row["cab_type"] = $type;
		return $this->_table->getDbTable()->insert($row);
	}
	/**
	* 更新
	* @param array $row
	* @param int $type
	* @param int $customerId
	*/
	public function update($row,$type,$customerId = null){
		$customerId = $this->getCustomerId($customerId);
		if($this->get($type,$customerId)){
			return $this->_table->update($row,$type,$this->getCustomerId($customerId));
		}
		return $this->add($row,$type,$customerId);
	}
	/**
	* 删除
	* @param array $row
	* @param int $type
	* @param int $customerId
	*/
	public function delete($row,$type,$customerId = null){
		$customerId = $this->getCustomerId($customerId);
		if($this->get($type,$customerId)){
			return $this->_table->update($row,$type,$this->getCustomerId($customerId));
		}
	}
	
	/**
	* 查找
	* @param int $type
	* @param int $customerId
	*/
	public function get($type,$customerId=null){
		$customerId = $this->getCustomerId($customerId);
		$address = $this->_table->getByTypeAndCustomerId($type,$customerId);
		if($address instanceof Zend_Db_Table_Row){
			return $address->toArray();
		}
		return $address;
	}
	/**
	* 查询当前客户id
	* @param int|null customerId
	* @return int
	*/
	public function getCustomerId($customerId = null){
		if($customerId == null){
			$loginInfo = $this->getLoginInfo();
			$customerId = $loginInfo->customer['customer_id'];
		}
		return $customerId;
	}
	
	/**
	* 取得用户登录信息
	* @return Zend_Session_Namespace
	*/
	public function getLoginInfo(){
		$sessionUser = new Zend_Session_Namespace("customer");
		return $sessionUser;
	}
	
	public function validateAddressInfo($row){
		$error = array();
		foreach($row as $key => $value){
			if($key == "cab_country_id" && $value == 0){
				$error[$key] = "This field is required";
			}
			if($value == ""){
				$error[$key] = "This field is required";
			}
		}
		return $error;
	}
}